package com.haiheng.module_main

import android.content.Intent
import android.os.Bundle
import android.os.PersistableBundle
import android.os.Vibrator
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.module_main.databinding.ActivityScanBinding
import com.haiheng.module_main.zing.qrcode.BarcodeType
import com.haiheng.module_main.zing.qrcode.QRCodeView

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2021/12/2 0002
 * @Version: 1.0
 */
class ScanActivity : AppCompatActivity(), QRCodeView.Delegate {

    val RESULT_OK = 600

    private lateinit var binding: ActivityScanBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityScanBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.zxingview.setDelegate(this)
        binding.includeTile.tvTitle.setText("扫一扫")
        binding.includeTile.tvClear.visibility = View.GONE
        binding.includeTile.tvCarName.visibility = View.GONE
        binding.includeTile.sflBack.setOnClickListener { finish() }
        binding.zxingview.setType(BarcodeType.ONE_DIMENSION, null) // 只识别一维条码

    }

    override fun onStart() {
        super.onStart()
        vibrate()
        binding.zxingview.startCamera() // 打开后置摄像头开始预览，但是并未开始识别

        //mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        //mZXingView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT); // 打开前置摄像头开始预览，但是并未开始识别
        binding.zxingview.startSpotAndShowRect() // 显示扫描框，并开始识别

    }

    override fun onDestroy() {
        super.onDestroy()
        binding.zxingview.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        binding.zxingview.startSpot()
    }
    override fun onStop() {
        binding.zxingview.stopCamera() // 关闭摄像头预览，并且隐藏扫描框
        super.onStop()
    }

    private fun vibrate() {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
    }

    override fun onScanQRCodeSuccess(result: String?) {
        LogUtils.i("扫码结果：$result")
        var newResult = ""
        if (result != null) {
            if (result.contains("-")){
                newResult = result.substring(0,result.indexOf("-"))
            }else{
                newResult = result
            }
        }
        //        ToastUtils.showShort(result);
        vibrate()
        binding.zxingview.stopSpot() // 开始识别
//        val intent = Intent(this,ScanResultActivity::class.java)
//        intent.putExtra("result", newResult)
//        startActivity(intent)
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {


    }

    override fun onScanQRCodeOpenCameraError() {
        ToastUtils.showShort("打开相机出错")
    }

}